/**
 * Created by liujie on 2017/11/12.
 */
/**
 * Created by liujie on 2017/10/11.
 * 监控管理
 */
var express = require('express');
var request = require('request');
var Mock = require('mockjs');
var url = require('url');
var qstr = require("querystring");
var fs = require("fs");
var pro = require('../../property/cuspro');
var auth = require('../../auth/auth');
var util = require('../../util/commonutil');
var router = express.Router();
var resultJSON = require('../common/resultJSON');

var cars = [
    {
        "id":1001,
        "address":"青岛市崂山区石老人海水浴场",
        "status":"1",
    },
    {
        "id":1002,
        "address":"青岛市崂山区科苑纬三路19号",
        "status":"0",
    },
    {
        "id":1003,
        "address":"青岛国际会展中心",
        "status":"0",
    },
    {
        "id":1004,
        "address":"青岛市市南区泰安路2号",
        "status":"3",
    },
    {
        "id":1005,
        "address":"山东省青岛市李沧区静乐路1号",
        "status":"2",
    },
    {
        "id":1006,
        "address":"山东省青岛市即墨滨海公路72号",
        "status":"2",
    }
];

var carTree = [
];
function getTrees(treeDatas) {
    carTree[0]["nodes"] = [];
    if(treeDatas && treeDatas.length){
        var treeItems = [];
        var rootTree = treeDatas[0];
        rootTree = getTreeData(treeDatas,rootTree);
        rootTree["text"] = treeDatas[0]["name"];
        rootTree["state"]= {
            expanded:true
        };
        carTree[0]["nodes"].push(rootTree);
    }
}

function getTreeData(treeDatas,treeitem) {
    if(treeDatas && treeDatas.length){
        treeitem["nodes"] = [];
        for(var i=0;i<treeDatas.length;i++){
            var _treeData = treeDatas[i];
            _treeData["text"] =_treeData["name"];
            if(_treeData["isCar"] == true){
                // _treeData["color"] = "#0ae";
                //warningType 1--在线 0-离线 2-在线停止 3-报警 5-超速
                if(_treeData["warningType"] == 0){
                    _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-black.png'></span>"+_treeData["text"]
                }else if(_treeData["warningType"] == 1){
                    _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-blue.png'></span>"+_treeData["text"]
                }
                else if(_treeData["warningType"] == 2){
                    _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-red.png'></span>"+_treeData["text"]
                }
                else if(_treeData["warningType"] == 3){
                    _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-red.png'></span>"+_treeData["text"]
                }
                else if(_treeData["warningType"] == 5){
                    _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-red.png'></span>"+_treeData["text"]
                }else{
                    _treeData["text"] = "<span class='icon isCar'></span>"+_treeData["text"]
                }
            }



            if(_treeData["parentId"] == treeitem["id"]){
                treeitem["nodes"].push(getTreeData(treeDatas,_treeData));
            }
        }
        return treeitem
    }
};

router.get('/',function (req, res, next) {
    res.render("report/dianhuoreportManage");
});
router.post('/queryTreeData',function (req, res, next) {
    carTree = [
        {
            text: "所有客户",
            state:{
                expanded:true
            },
            nodes:[]
        }
    ];
    var _online = req.param("online");
    var _url = pro.devServeraddr + "heb/baseCar/loadZTree";
    if(_online === "0"){
        _url = _url +"?online=0"
    }else if(_online === "1"){
        _url = _url +"?online=1"
    }
    console.log("--ur--"+_url);
    request({
        // url:"http://localhost:3001/testData/carTree.json",
        url:_url,
        method: "GET",
        // qs: {online:'0'}
    },function (error, response, body) {
        console.log(JSON.parse(body).length);
        getTrees(JSON.parse(body));
        res.json(carTree);
    });
});
router.post('/queryTreeNodeInfo',function (req,res,next) {
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByTrackCar",
        method: "POST",
        qs:req.body
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            console.log("ndoeinfo---"+body);
            if(result.success == true){
                resultJSON.isSuccess=true;
                resultJSON.data=result.data;
            }else{
                resultJSON.isSuccess=false;
                resultJSON.message="查询数据异常，请稍后重试！"
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(resultJSON);
    });



    // res.json(treeNodes)
});
router.post('/queryHistotryInfo',function (req,res,next) {
    request({
        url:pro.devServeraddr + "heb/hisGpsInfo/queryTableGpsData",
        method: "POST",
        qs:req.body
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            console.log("ndoeinfo---"+body);
            if(result.success == true){
                resultJSON.isSuccess=true;
                resultJSON.data=result.rows;
            }else{
                resultJSON.isSuccess=false;
                resultJSON.message="查询数据异常，请稍后重试！"
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(resultJSON);
    });



    // res.json(treeNodes)
});
router.get('/queryCarStatus',function (req,res,next) {
    var carsJSON = [];
    var status = req.param("tabCode");
    for(var i=0;i<cars.length;i++){
        var car = cars[i];
        if(car["status"] == status){
            carsJSON.push(car);
        }
    }
    res.json(carsJSON)
});



router.get('/listByCountCar',function (req,res,next) {
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByCountCar",
        method: "GET",
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            if(result.success){
                resultJSON.isSuccess=true;
                resultJSON.data=result.data;
            }else{
                resultJSON.isSuccess=false;
                resultJSON.message="查询数据异常，请稍后重试！"
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(resultJSON);
    });
});
router.get('/his', function(req, res, next) {
    auth.checkAuth(req, res, next);
    var pathname = url.parse(req.url).pathname;  //pathname => list
    var arg = url.parse(req.url, true).query;   //arg1 => {name:'a',id:'5'}
    var query=req.query;//参数
    var carId=query.carId;
    var carNo=query.carNo;
    if(!carId){
        carId="0"
    }
    if(!carNo){
        carNo=""
    }
    res.render('map/oldMonitor',{jw:pro.jw,flag: false,serverurl:pro.serveraddr,carId:carId,carNo:carNo});

});
/**
 * 查询在线车辆接口
 */
router.post('/listByRealOnLineCar',function (req,res,next) {
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByRealOnLineCar",
        method: "POST",
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            var jsonResult = {
                total:0,
                rows:[]
            };
            if(result.success == true){
                console.log("rows:"+result.rows.length);
                jsonResult.total = result.rows.length;
                jsonResult.rows = result.rows;
            }else{
                resultJSON.isSuccess=false;
                resultJSON.message="查询数据异常，请稍后重试！"
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});

/**
 * 查询在线车辆树接口
 */
router.post('/listByRealOnLineCarTree',function (req,res,next) {
    carTree = [
        {
            text: "所有客户",
            state:{
                expanded:true
            },
            nodes:[]
        }
    ];
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByRealOnLineCar",
        method: "POST",
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            var jsonResult = {
                total:0,
                rows:[]
            };
            if(result.success == true){
                console.log("rows:"+result.rows.length);
                jsonResult.total = result.rows.length;
                jsonResult.rows = result.rows;
                getTrees(result.rows);
            }else{
                resultJSON.isSuccess=false;
                resultJSON.message="查询数据异常，请稍后重试！"
            }
        }else{
            resultJSON.isSuccess=false;
            resultJSON.message="查询数据异常，请稍后重试！"
        }
        res.json(carTree);
    });

    // res.json(treeNodes)
});
/**
 * 查询离线车辆接口
 */
router.post('/listByRealOutLineCar',function (req,res,next) {

    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByRealOutLineCar",
        method: "POST"
    },function (error, response, body) {
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            var jsonResult = {
                total:0,
                rows:[],
                isSuccess:false,
                message:""
            };
            if(result.success == true){
                jsonResult.total = result.rows.length;
                jsonResult.rows = result.rows;
                jsonResult.isSuccess = true;
            }else{
                jsonResult.isSuccess = false;
                jsonResult.message = result.msg ? result.msg : "离线表格查询数据异常，请稍后重试！";
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});

/**
 * 查询关注车辆接口
 */
router.post('/listByCarIds',function (req,res,next) {
    var allCarIds = req.param("allCarIds");
    var qs=req.body;
    console.log("关注车辆参数:"+allCarIds);
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByCarIds",
        method: "POST",
        qs:qs
    },function (error, response, body) {
        console.log("关注车辆："+body);
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            var jsonResult = {
                total:0,
                rows:[],
                isSuccess:false,
                message:""
            };
            if(result.success == true){
                jsonResult.total = result.rows.length;
                jsonResult.rows = result.rows;
                jsonResult.isSuccess = true;
            }else{
                jsonResult.isSuccess = false;
                jsonResult.message = result.msg ? result.msg : "离线表格查询数据异常，请稍后重试！";
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});

/**
 * 查询报警信息
 */
router.post('/listByCarWaring',function (req,res,next) {
    request({
        url:pro.devServeraddr + "heb/realGpsInfo/listByCarWaring",
        method: "POST"
    },function (error, response, body) {
        console.log("报警信息--"+body);
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            var jsonResult = {
                total:0,
                rows:[],
                isSuccess:false,
                message:""
            };
            if(result.success == true){
                jsonResult.total = result.rows.length;
                jsonResult.rows = result.rows;
                jsonResult.isSuccess = true;
            }else{
                jsonResult.isSuccess = false;
                jsonResult.message = result.msg ? result.msg : "离线表格查询数据异常，请稍后重试！";
            }
        }else{
            jsonResult.isSuccess = false;
            jsonResult.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(jsonResult);
    });

    // res.json(treeNodes)
});
/**
 * 处理报警信息
 */
router.post('/updateWarningType',function (req,res,next) {
    var id = req.param("id");
    var type =1;
    request({
        url:pro.devServeraddr + "heb/tabWaringInfo/updateType",
        method: "POST",
        qs:{
            "id":id,
            "type":type
        }
    },function (error, response, body) {
        console.log("处理报警信息--"+body);
        if(!error && response.statusCode == 200){
            var result = JSON.parse(body);
            resultJSON.data = result
        }else{
            resultJSON.isSuccess = false;
            resultJSON.message = "离线表格查询数据异常，请稍后重试！";
        }
        res.json(resultJSON);
    });

    // res.json(treeNodes)
});
module.exports =router;